#pragma once
#include <iostream>
#include <pthread.h>
#include <cerrno>
#include <string>
#include <string.h>
#include <functional>
using namespace std;

// typedef void (*func_t)(void*);  //函数指针

//封装线程类
class Thread
{
public:
typedef enum
{
    NEW = 0,
    RUNNING,
    EXITED
}ThreadStatus;
// typedef void (*func_t)(void*);  //函数指针

using func_t = function<void()>;  //回调函数的类型
public:
   //构造
   Thread(int num,func_t func):_id(0),_func(func),_status(NEW)
    {
        // char* name  = new char[64];  //等下试试不加new
         char name[64];
        snprintf(name,64,"thread-%d",num);
        _name = name;
    }

    string& threadname()
    {
        return _name;
    }
    pthread_t threadid()
    {
        return _id;   //当线程未进行运行时，id为0
    }
    int threadstatus()
    {
        return _status;
    }
    static void* runHelper(void* args)  //如果不加static，这个函数实际参数不止args一个，还有一个默认参数this
    {
       Thread* ts = static_cast<Thread*> (args);
        // ts->_func(ts->_args);  //对函数进行回调
        (*ts)();  //对函数进行回调
    }
    void operator()()  //这个不用写，函数也能正常进行回调
    {
        _func();
    }
    void run()  //线程运行相关方法
    {
       int n = pthread_create(&_id,nullptr,runHelper,this); //传this指针参数
       if(n != 0) 
       {
        cerr<<"crearte error:"<<n<<strerror(n)<<endl;
       }
       _status = RUNNING;
    }
    void join() //线程等待
    {
       int n = pthread_join(_id,nullptr);
       if(n != 0) 
       {
        cerr<<"join error:"<<n<<strerror(n)<<endl;
       }
       _id = 0;
       _status = EXITED;
    }
   //析构
   ~Thread()
   {}
  
private:
pthread_t _id;  //线程id
string _name; //线程名
func_t _func;  //调用回调函数
ThreadStatus _status;  //线程状态   
};
